dojo.provide('ph.rfid.PhidgetReader');

dojo.require('ph.rfid.Reader');
ph.require('com.phidgets.RFIDPhidget');
ph.require('com.phidgets.event.TagGainListener');
ph.require('com.phidgets.event.TagLossListener');

dojo.declare('ph.rfid.PhidgetReader', ph.rfid.Reader, {
  constructor: function() {
    this._reader = new com.phidgets.RFIDPhidget();
    
    this._reader.addTagGainListener(new JavaAdapter(com.phidgets.event.TagGainListener, {
      tagGained: dojo.hitch(this, function(evt) { 
        this.onTagEnter(new ph.event.Event('enter', { tag: ph.str(evt.value) }));
      })
    }));
    
    this._reader.addTagLossListener(new JavaAdapter(com.phidgets.event.TagLossListener, {
      tagLost: dojo.hitch(this, function(evt) {
        this.onTagLeave(new ph.event.Event('leave', { tag: ph.str(evt.value) }));
      })
    }));
    
    this.__defineGetter__('hasTag', this._hasTag);
    this.__defineGetter__('lastTag', this._lastTag);
    this.__defineGetter__('led', this._led);
    this.__defineSetter__('led', this._led_set);
    this.__defineGetter__('antenna', this._antenna);
    this.__defineSetter__('antenna', this._antenna_set);
  },
  
  open: function() {
    try {
      this._reader.openAny();
      this._reader.waitForAttachment(1000);
    } catch(e) {
      throw new ph.rfid.Exception('RFID Exception. Are you sure the Phidgets RFID Reader is connected?');
    }
  },
  
  close: function() {
    this._reader.close();
  },
  
  onTagEnter: function() {},
  onTagLeave: function() {},
  
  _hasTag: function() {
    try {
      return this._reader.getTagStatus();
    } catch(e) {
      return false;
    }
  },
  
  _lastTag: function() {
    try {
      return this._reader.getLastTag();
    } catch(e) {
      return null;
    }
  },
  
  _led: function() {
    try {
      return this._reader.getLEDOn();
    } catch(e) {
      throw new ph.rfid.Exception();
    }
  },
  
  _led_set: function(state) {
    try {
      return this._reader.setLEDOn(state === true);
    } catch(e) {
      throw new ph.rfid.Exception();
    }
  },
  
  _antenna: function() {
    try {
      return this._reader.getAntennaOn();
    } catch(e) {
      throw new ph.rfid.Exception();
    }
  },
  
  _antenna_set: function(state) {
    try {
      return this._reader.setAntennaOn(state === true);
    } catch(e) {
      throw new ph.rfid.Exception();
    }
  }
});